import requests
from playwright.sync_api import sync_playwright
import re
import time
import datetime


class MaoyanCralwer():
    def __init__(self) -> None:
        self.user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.125 Safari/537.36'
        self.random = 9
        self.timestamp = None
        self.browser = None
        self.page = None
        self.cookies = None

    def reqInfo(self, movie_id):
        headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Cache-Control': 'no-cache',
            'Connection': 'keep-alive',
            'Pragma': 'no-cache',
            'Sec-Fetch-Dest': 'empty',
            'Sec-Fetch-Mode': 'cors',
            'Sec-Fetch-Site': 'same-origin',
            'User-Agent': self.user_agent,
            'X-Requested-With': 'XMLHttpRequest',
            'sec-ch-ua': '"Not-A.Brand";v="24", "Chromium";v="14"',
            'sec-ch-ua-mobile': '?0',
            'sec-ch-ua-platform': '"Windows"',
        }
        self.timestamp = int(datetime.datetime.now().timestamp() * 1000)
        signKey = self.generateSignKey()
        params = {
            'timeStamp': self.timestamp,
            'index': self.random,
            'signKey': signKey,
            'channelId': '40011',
            'sVersion': '1',
            'webdriver': 'false',
        }

        response = requests.get(
            f'https://www.maoyan.com/ajax/films/{movie_id}',
            headers=headers, params=params, cookies=self.cookies
        )
        return response.text

    def generateSignKey(self):
        if not self.browser:
            playwright = sync_playwright().start()
            browser_type = playwright.chromium
            self.browser = browser_type.launch(headless=False, args=["--disable-blink-features=AutomationControlled"])
            context = self.browser.new_context()
            self.page = context.new_page()

            def handle_js(route):
                if re.search(r'chunk-libs_1741760113622_5c1094a7.js', route.request.url):
                    response = route.fetch()
                    content = response.body()
                    # 注意要使用格式化前的代码进行匹配，去除空格
                    content = content.replace(b'e.default=x', b'window.uuuxx=x;e.default=x')
                    route.fulfill(body=content)
                else:
                    route.continue_()

            self.page.set_default_timeout(0)
            self.page.route("**/*.js", handle_js)
            self.page.goto(f'https://www.gdtv.cn/channels/3#30')
            self.transformCookie(context.cookies())
        message = f'method=GET&timeStamp={self.timestamp}&User-Agent={self.user_agent}&index={self.random}&channelId=40011&sVersion=1&key=A013F70DB97834C0A5492378BD76C53A'
        signature = self.page.evaluate(f'''
            () => {{
                return new Promise((resolve) => {{
                    window.uuuxx('GET', 'https://gdtv-api.gdtv.cn/api/channel/v1/news?beginScore=1743075298000&channelId=46&pageSize=11', '').then((t) => {{
                        resolve(t);
                    }});
                }});
            }}
        ''')
        return signature

    def transformCookie(self, cookies_list):
        self.cookies = {c['name']: c['value'] for c in cookies_list}


maoyanCralwer = MaoyanCralwer()

maoyanCralwer.generateSignKey()
# res = maoyanCralwer.reqInfo('1470379')
# print(res)
pass